//
//  EFLoginViewController.m
//  EnjogFood
//
//  Created by guocheng on 2017/5/2.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFLoginViewController.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "iToast.h"
#import "WXApi.h"
#import "EFSepecialItem.h"

@interface EFLoginViewController ()<UITextFieldDelegate>
@property(strong,nonatomic) UITextField *phoneTextF;
@property(strong,nonatomic) UITextField *pwdTextF;
@property(strong,nonatomic) UIView *phoneLineV;
@property(strong,nonatomic) UIView *pwdLineV;
@property(strong,nonatomic) UIButton *loginBtn;
@property(strong,nonatomic) UIButton *sendMessageBtn;
@property(strong,nonatomic) UIButton *deletePwdBtn;
@property(strong,nonatomic) UIButton * wxLogoBtn;
@property(strong,nonatomic) UIButton *  wxLoginTextBtn;


@property (strong, nonatomic) NSTimer *authCodeCountTimer;
@property (assign, nonatomic) NSInteger authCodeTimerCounter;

@property (strong, nonatomic) TPKeyboardAvoidingScrollView * scrollView;

@property int condtion;
@property BOOL phoneValid;
@property BOOL pwdValid;
@end

@implementation EFLoginViewController


- (instancetype)init{
    self = [super init];
    if (self) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.title = @"登录";
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxLoginSuccess:) name:@"WXLoginSuccess" object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    // Do any additional setup after loading the view.
    self.enableBackButton = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initView{
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.phoneTextF];
    [self.scrollView addSubview:self.phoneLineV];
    [self.scrollView addSubview:self.sendMessageBtn];
    [self.scrollView addSubview:self.pwdTextF];
    [self.scrollView addSubview:self.pwdLineV];
//    [self.scrollView addSubview:self.deletePwdBtn];
    [self.scrollView addSubview:self.loginBtn];
    [self.scrollView addSubview:self.wxLogoBtn];
    [self.scrollView addSubview:self.wxLoginTextBtn];
    
    self.pwdTextF.hidden = true;
    self.pwdLineV.hidden = true;
//    self.deletePwdBtn.hidden = true;
    
    _condtion = 0;
    _phoneValid = false;
    _pwdValid = false;
}

+ (void)presentLoginViewController:(UIViewController *)controller withCompleteBlock:(void (^) (void))block {
    EFLoginViewController *login = [[EFLoginViewController alloc] init];
    login.successBlock = block;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
    [controller presentViewController:nav animated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)onClickSendMessageBtn{
    self.sendMessageBtn.enabled = NO;
    [APP_CONTEXT.net getVerifycodeWithPhoneNum:self.phoneTextF.text  OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        self.sendMessageBtn.enabled = YES;
        if (code == 0) {
            [self startAuthCodeTimer];
            self.pwdTextF.hidden = false;
            self.pwdLineV.hidden = false;
        }else{
            [[iToast makeText:message] show];
        }
    }];
    
}

-(void)onClickLoginBtn{
    NSString* phone = self.phoneTextF.text;
    if (phone.length == 0) {
        [[iToast makeText:@"请输入手机号码"] show];
        return;
    }
    NSString* code = self.pwdTextF.text;
    if ( code.length == 0) {
        [[iToast makeText:@"请输入验证码"] show];
        return;
    }
    [self showHUD];
    [APP_CONTEXT.net loginWithPhoneNum:phone code:code OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        [self.HUD hide:YES];
        if (code == 0) {
            if ([info objectForKey:@"token"]) {
                APP_CONTEXT.accountManager.accountInfo.token = [info objectForKey:@"token"];
            }
            APP_CONTEXT.accountManager.accountInfo.phone = phone;
            [APP_CONTEXT.accountManager persistenceAccountInfo];
            [[NSNotificationCenter defaultCenter] postNotificationName:IC_ACCOUNT_DID_LOGIN_NOTIFICATION object:nil];
            [APP_CONTEXT.net saveGeTuiInfoPhone:APP_CONTEXT.accountManager.accountInfo.phone openid:APP_CONTEXT.accountManager.accountInfo.openid clientId:APP_CONTEXT.accountManager.accountInfo.cliendId OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
                if (code == 0) {
                    
                }
            }];

            [self syncShopCart];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            [[iToast makeText:message] show];
        }
    }];
    
    
   
}

-(void)onClickWxLogin:(UIButton*)sender{
    [self showHUD];
    [self sendAuthRequest];
}

- (void)sendAuthRequest {
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = EFWXScope;
    req.state = EFWXState;
    [WXApi sendReq:req];
}


-(TPKeyboardAvoidingScrollView*)scrollView{
    if(_scrollView == NULL){
        _scrollView = [[TPKeyboardAvoidingScrollView alloc]initWithFrame: CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _scrollView.contentSize =  CGSizeMake(kScreenWidth, kScreenHeight - kStatusBarHeight);
    }
    return _scrollView;
}


-(UITextField *)phoneTextF{
    if(_phoneTextF == NULL){
        _phoneTextF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 20.5f - 19.5f, 19)];
        _phoneTextF.left = 20.5f;
        _phoneTextF.top = 59.8f;
        _phoneTextF.font = [UIFont systemFontOfSize:15];
        _phoneTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _phoneTextF.delegate = self;
        _phoneTextF.placeholder = @"请输入手机号";
    }
    
    return _phoneTextF;
}

-(UIView*)phoneLineV{
    if(_phoneLineV == NULL){
        _phoneLineV = [[UIView alloc] initWithFrame:CGRectMake(0, 0,0,0)];
        _phoneLineV.width = kScreenWidth - 20.5f - 19.5f;
        _phoneLineV.height = 1;
        _phoneLineV.left = 20.5f;
        _phoneLineV.top = 88;
        [_phoneLineV setBackgroundColor:RGBCOLOR(0xDDDDDD)];
    }
    return _phoneLineV;
}

-(UITextField *)pwdTextF{
    if(_pwdTextF == NULL){
        _pwdTextF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0,  kScreenWidth - 20.5f - 19.5f, 19)];
        _pwdTextF.left = 20.5;
        _pwdTextF.top = 108.8f;
        _pwdTextF.font = [UIFont systemFontOfSize:15];
        _pwdTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _pwdTextF.delegate = self;
        _pwdTextF.placeholder = @"输入验证码";
        _pwdTextF.clearButtonMode = UITextFieldViewModeAlways;
    }
    return _pwdTextF;
}

-(UIView*)pwdLineV{
    if(_pwdLineV == NULL){
        _pwdLineV =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _pwdLineV.width = kScreenWidth - 20.5f - 19.5f;
        _pwdLineV.height = 1;
        _pwdLineV.left = 20.5f;
        _pwdLineV.top = 136;
        [_pwdLineV setBackgroundColor:RGBCOLOR(0xDDDDDD)];
    }
    return _pwdLineV;
}
-(UIButton*)deletePwdBtn{
    if(_deletePwdBtn == NULL){
        _deletePwdBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        _deletePwdBtn.right = kScreenWidth - 20;
        _deletePwdBtn.top = 106;
        [_deletePwdBtn setBackgroundImage:IMG(@"content_icon_delete") forState:UIControlStateNormal];
    }
    return _deletePwdBtn;
}

-(UIButton*)sendMessageBtn{
    if(_sendMessageBtn == NULL){
        _sendMessageBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 24)];
        _sendMessageBtn.right = kScreenWidth - 19;
        _sendMessageBtn.top = 54;
        [_sendMessageBtn setTitleColor:kBlack999 forState:UIControlStateNormal];
        _sendMessageBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
        _sendMessageBtn.titleLabel.textColor = kBlack999;
        [_sendMessageBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_sendMessageBtn setBackgroundImage:IMG(@"content_btn_msg1") forState:UIControlStateNormal];
        [_sendMessageBtn addTarget:self action:@selector(onClickSendMessageBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendMessageBtn;
}

-(UIButton*)loginBtn{
    if(_loginBtn == NULL){
        _loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth - 40, 40)];
        _loginBtn.left = 20;
        _loginBtn.top = 184;
        _loginBtn.layer.cornerRadius = 4;
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setTitle:@"登录" forState:UIControlStateDisabled];
        _loginBtn.enabled = false;
        [_loginBtn setBackgroundColor:kBlackDDD];
        [_loginBtn addTarget:self action:@selector(onClickLoginBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}


-(UIButton*)wxLogoBtn{
    if(_wxLogoBtn == NULL){
        _wxLogoBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 13.3f, 11.6f)];
        _wxLogoBtn.left = (kScreenWidth - _wxLogoBtn.width - 120)/2;
        _wxLogoBtn.top = 255;
        [_wxLogoBtn setImage:IMG(@"wechat") forState:UIControlStateNormal];
        [_wxLogoBtn addTarget:self action:@selector(onClickWxLogin:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _wxLogoBtn;
}

-(UIButton*)wxLoginTextBtn{
    if(_wxLoginTextBtn == NULL){
        _wxLoginTextBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 120, 17)];
        _wxLoginTextBtn.left = _wxLogoBtn.right ;
        _wxLoginTextBtn.top = 252.8f;
        [_wxLoginTextBtn setTitleColor:kBlack999 forState:UIControlStateNormal];
        _wxLoginTextBtn.titleLabel.textColor = kBlack999;
        _wxLoginTextBtn.titleLabel.font =[UIFont systemFontOfSize:15.0f];
        [_wxLoginTextBtn setTitle:@"使用微信登录" forState:UIControlStateNormal];
        [_wxLoginTextBtn addTarget:self action:@selector(onClickWxLogin:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _wxLoginTextBtn;
}


- (void)startAuthCodeTimer {
    self.sendMessageBtn.enabled = NO;
    self.authCodeTimerCounter = 30;
    
    self.authCodeCountTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                               target:self
                                                             selector:@selector(onAuthCodeTimer)
                                                             userInfo:nil
                                                              repeats:YES];
    
    NSString *leftSec = [NSString stringWithFormat:@"%ld秒", (long)self.authCodeTimerCounter];
    [self.sendMessageBtn setTitle:leftSec forState:UIControlStateNormal];
    [self.sendMessageBtn setTitle:leftSec forState:UIControlStateDisabled];
}

- (void)endAuthCodeTimer {
    [self.authCodeCountTimer invalidate];
    self.authCodeCountTimer = nil;
    self.sendMessageBtn.userInteractionEnabled = YES;
    self.sendMessageBtn.enabled = self.phoneTextF.text.length == 11;
    [self.sendMessageBtn setTitle:@"再次发送" forState:UIControlStateNormal];
    [self.sendMessageBtn setTitle:@"再次发送" forState:UIControlStateDisabled];
    [self.sendMessageBtn setBackgroundImage:IMG(@"content_btn_msg3") forState:UIControlStateNormal];
}

- (void)onAuthCodeTimer{
    self.authCodeTimerCounter--;
    if (self.authCodeTimerCounter == 0) {
        [self endAuthCodeTimer];
    } else {
        NSString *leftSec = [NSString stringWithFormat:@"%ld秒", (long)self.authCodeTimerCounter];
        self.sendMessageBtn.enabled = NO;
        self.sendMessageBtn.titleLabel.text = leftSec;
        [self.sendMessageBtn setTitle:leftSec forState:UIControlStateNormal];
        [self.sendMessageBtn setTitle:leftSec forState:UIControlStateDisabled];
    }
}


#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.phoneTextF) {
        NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (str.length >= 11) {
            self.sendMessageBtn.enabled = YES;
            _phoneValid = true;
        }else{
            self.sendMessageBtn.enabled = NO;
            _phoneValid = false;
        }
        
        if(_phoneValid && _pwdValid){
            self.loginBtn.enabled = YES;
            [self.loginBtn setBackgroundColor:RGBCOLOR(0x69ba45)];
        }else{
            self.loginBtn.enabled = FALSE;
            [self.loginBtn setBackgroundColor:kBlackDDD];
        }
        
        return str.length <= 11;
    }else  if (textField == self.pwdTextF) {
        NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (str.length >= 1) {
            self.deletePwdBtn.hidden = false;
            _pwdValid = true;
        }else{
            self.deletePwdBtn.hidden = true;
            _pwdValid = false;
        }
        
        if(_phoneValid && _pwdValid){
            self.loginBtn.enabled = YES;
            [self.loginBtn setBackgroundColor:RGBCOLOR(0x69ba45)];
        }else{
            self.loginBtn.enabled = FALSE;
            [self.loginBtn setBackgroundColor:kBlackDDD];
        }
        
        return str.length <= 10;
    }
    return YES;
}


//#pragma mark - WXLogin
- (void)wxLoginSuccess:(NSNotification *)n{
    NSDictionary *dic = n.userInfo;
    [APP_CONTEXT.net registerWX:[dic objectForKey:@"openid"] unionid:[dic objectForKey:@"unionid"] OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        [self.HUD hide:YES];
        if(code == 0){
           
            //记录token userId
            if ([info objectForKey:@"user_id"]) {
                APP_CONTEXT.accountManager.accountInfo.userId = [info objectForKey:@"user_id"];
                APP_CONTEXT.accountManager.accountInfo.profileInfo.userId = [info objectForKey:@"user_id"];
            }
            if ([info objectForKey:@"token"]) {
                APP_CONTEXT.accountManager.accountInfo.token = [info objectForKey:@"token"];
            }
            [APP_CONTEXT.net saveGeTuiInfoPhone:APP_CONTEXT.accountManager.accountInfo.phone openid:APP_CONTEXT.accountManager.accountInfo.openid clientId:APP_CONTEXT.accountManager.accountInfo.cliendId OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
                if (code == 0) {
                    
                }
            }];

            [APP_CONTEXT.accountManager persistenceAccountInfo];
            [[NSNotificationCenter defaultCenter] postNotificationName:IC_ACCOUNT_DID_LOGIN_NOTIFICATION object:nil];
             [self syncShopCart];
            [self dismissViewControllerAnimated:YES completion:nil];

        }
    }];
}

-(void)syncShopCart{
    //扫码
    if(APP_CONTEXT.shoppingCartManager.scanCount > 0 ){
        //转换数组
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
        for (EFSepecialItem *item in APP_CONTEXT.shoppingCartManager.scanProductsCart) {
            NSDictionary *dic = [NSDictionary dictionary];
            dic = @{
                    @"id":item.id,
                    @"qty":item.qty,
                    @"barcode":item.barcode != nil ? item.barcode : @""
                    };
            [array addObject:dic];
        }
        
        [APP_CONTEXT.net updateCartList:array total:[NSNumber numberWithUnsignedInteger:APP_CONTEXT.shoppingCartManager.scanCount] type:[NSNumber numberWithInt:1] OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
           
        }];
    }
    
    //商城
    if(APP_CONTEXT.shoppingCartManager.storeCount > 0 ){
        //转换数组
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
        for (EFSepecialItem *item in APP_CONTEXT.shoppingCartManager.storeProductsCart) {
            NSDictionary *dic = [NSDictionary dictionary];
            dic = @{
                    @"id":item.id,
                    @"qty":item.qty != nil?item.qty:[NSNumber numberWithInteger:1],
                    @"barcode":item.barcode != nil ? item.barcode : @""
                    };
            [array addObject:dic];
        }
        
        [APP_CONTEXT.net updateCartList:array total:[NSNumber numberWithUnsignedInteger:APP_CONTEXT.shoppingCartManager.storeCount] type:[NSNumber numberWithInt:0] OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            
        }];
    }
}


@end
